﻿/* Sorting an array means to arrange its elements in increasing order. 
 * Write a program to sort an array. Use the "selection sort" algorithm: 
 * Find the smallest element, move it at the first position, 
 * find the smallest from the rest, 
 * move it at the second position, etc.
 */

using System;
using System.Collections.Generic;

class SortingMyArray
{
    static void Main()
    {
        bool iProvided = false;
        uint N;
        do
        {
            if (iProvided == true) Console.WriteLine("Error! Please enter an integer number. ");
            else iProvided = true;
            Console.Write("Enter how many elements the array will have: ");
        } while (UInt32.TryParse(Console.ReadLine(), out N) == false || iProvided == false);
        //Console.WriteLine(N);

        int[] numbers = new int[N]; //make some space for the array
        for (int i = 0; i < N; i++)
        {
            //restart iProvided so we have proper error checking available
            iProvided = false;
            do
            {
                if (iProvided == true) Console.WriteLine("Error! Please enter an integer number. ");
                else iProvided = true;
                Console.Write("Enter element {0}: ", i+1);
            } while (Int32.TryParse(Console.ReadLine(), out numbers[i]) == false || iProvided == false);

        }
        //sort
        int? iMin = null;
        
        //sorting using selection sort
        for (int i = 0; i < numbers.Length-1; i++)
        {
            iMin = i;
            for (int j = i + 1; j < numbers.Length; j++)
            {
                if (numbers[j] < numbers[(int)iMin]) iMin = j;
            }
            if (iMin != i)
            {
                int tmp = numbers[i];
                numbers[i] = numbers[(int)iMin];
                numbers[(int)iMin] = tmp;
            }
        }
        Console.WriteLine("Sorted: ");
        for (int i = 0; i < numbers.Length; i++) Console.WriteLine(numbers[i]);
    }
}
